package com.pur.zsms.financing.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.cglib.beans.BeanCopier;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.pur.zsms.common.exception.GenericException;
import com.pur.zsms.common.support.PageController;
import com.pur.zsms.common.support.PaginationSupport;
import com.pur.zsms.cost.po.CostPo;
import com.pur.zsms.cost.po.CostSubPo;
import com.pur.zsms.cost.service.ICostService;
import com.pur.zsms.financing.service.IFinancingService;
import com.pur.zsms.financing.vo.FinancingVo;
import com.pur.zsms.financing.vo.PictureVo;
import com.pur.zsms.matermanage.mater.vo.MaterVo;
import com.pur.zsms.ordercustommanage.vo.OrderCustVo;
import com.pur.zsms.ordercustommanage.vo.SelectMaterVo;
import com.pur.zsms.pmsnmanage.role.vo.RoleVo;
import com.pur.zsms.pmsnmanage.user.po.UserPo;
import com.pur.zsms.pmsnmanage.user.po.UserRolePo;
import com.pur.zsms.pmsnmanage.user.service.IUserService;
import com.pur.zsms.pmsnmanage.user.vo.UserVo;
import com.pur.zsms.pmsnmanage.user.web.UserControllor;
import com.pur.zsms.shopmanage.service.IShopService;
import com.pur.zsms.shopmanage.vo.ShopVo;
import com.pur.zsms.supplier.po.ShopSupplierTypePo;
import com.pur.zsms.supplier.po.SupplierPo;
import com.pur.zsms.supplier.service.ISupplierService;
import com.pur.zsms.supplier.vo.ShopSupplierVo;
import com.pur.zsms.supplier.vo.SupplierVo;
import com.pur.zsms.systemsetting.datadictionary.service.IDataDictionaryService;
import com.pur.zsms.turnover.po.TurnoverPo;
import com.pur.zsms.turnover.po.TurnoverSubPo;
import com.pur.zsms.turnover.service.ITurnoverService;
import com.pur.zsms.turnover.vo.TurnoverVo;
import com.pur.zsms.unit.service.IUnitService;
import com.pur.zsms.unit.vo.UnitCommentVo;
import com.pur.zsms.unit.vo.UnitMenuVo;
import com.pur.zsms.unit.vo.UnitVo;

/**
 * 营业额
 * 
 * @author zhou
 * 
 */
@Controller
@RequestMapping(value = "/financing")
public class FinancingController {
	@SuppressWarnings("unused")
	private static final Logger log = LoggerFactory.getLogger(FinancingController.class);
	protected int page = 1;

	protected int pageSize = 15;

	PaginationSupport pageList;

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	@Resource(name = "costService")
	private ICostService costService;

	@Resource(name = "turnoverService")
	private ITurnoverService turnoverService;

	@Resource(name = "financingService")
	private IFinancingService financingService;

	@Resource(name = "dictionaryService")
	private IDataDictionaryService dataDictionaryService;

	@Resource(name = "userService")
	private IUserService userService;

	@Resource(name = "shopService")
	private IShopService shopService;

	@RequestMapping(value = "/listFinancingListForCust.do")
	@ResponseBody
	public String listFinancingListForCust(@RequestParam(required = false) String page, @RequestParam(required = false) String rows,
			FinancingVo tFinancingVo, HttpSession session) throws GenericException, IllegalAccessException, InvocationTargetException {
		JSONObject json = new JSONObject();
		if (page == null || page.equals(""))
			page = "1";
		if (rows == null || rows.equals(""))
			rows = "10";

		if (tFinancingVo.getInitFlag() == 0) {
			json.put("success", false);
			json.put("total", 0);
			return json.toString();
		}
		UserPo userInfo = (UserPo) session.getAttribute("user");
		long shopId = shopService.getShopIdoByUserId(userInfo.getUserId());
		if (tFinancingVo.getCustId() == 0) {
			tFinancingVo.setCustId(shopId);
		}
		PageController pageController = new PageController(Integer.parseInt(page), Integer.parseInt(rows));
		this.pageList = financingService.listFinancingList(pageController, tFinancingVo);

		List items = pageList.getItems();
		List<FinancingVo> financingVoList = new ArrayList<FinancingVo>();
		if (items != null) {
			for (int i = 0; i < items.size(); i++) {
				Object[] item = (Object[]) items.get(i);
				FinancingVo f = new FinancingVo();
				f.setTurnoverId(Long.valueOf(nullJudgeReturnString(item[0])));
				if (item[1] != null && !item[1].equals("")) {
					f.setCustId(Long.valueOf(nullJudgeReturnString(item[1])));
				}
				if (item[2] != null && !item[2].equals("")) {
					f.setCustName(nullJudgeReturnString(item[2]));
				}
				f.setTurnoverValueTotal(nullJudgeReturnString(item[3]));
				f.setTurnoverTypeDetialValue(nullJudgeReturnString(item[4]));
				f.setTurnoverState(nullJudgeReturnInt(item[5]));
				if (item[6] != null && !item[6].equals("")) {
					f.setDate(item[6].toString());
				}

				f.setCostId(Long.valueOf(nullJudgeReturnString(item[7])));
				if (item[8] != null && !item[8].equals("")) {
					f.setCustId(Long.valueOf(nullJudgeReturnString(item[8])));
				}
				if (item[9] != null && !item[9].equals("")) {
					f.setCustName(nullJudgeReturnString(item[9]));
				}
				f.setCostValueTotal(nullJudgeReturnString(item[10]));
				f.setCostTypeDetialValue(nullJudgeReturnString(item[11]));
				f.setCostState(nullJudgeReturnInt(item[12]));
				if (item[13] != null && !item[13].equals("")) {
					f.setDate(item[13].toString());
				}
				financingVoList.add(f);
			}
		}

		json.put("success", true);
		json.put("total", pageList.getTotalCount());
		json.put("rows", financingVoList);
		log.info("----" + json.toString());
		return json.toString();
	}

	public String nullJudgeReturnString(Object object) {
		if (object == null || object.toString().equals("")) {
			return "0";
		}
		return object.toString();
	}

	public int nullJudgeReturnInt(Object object) {
		if (object == null || object.toString().equals("")) {
			return 0;
		}
		return Integer.valueOf(object.toString());
	}

	@RequestMapping(value = "/preSaveFinancing.do", method = { RequestMethod.GET })
	public ModelAndView preSaveFinancing(TurnoverVo turnoverVo, HttpSession session) {
		Map map = new HashMap();
		UserPo userInfo = (UserPo) session.getAttribute("user");
		try {
			// UserVo userVo =
			// userService.getUserVoById(String.valueOf(userInfo.getUserId()));
			long shopId = shopService.getShopIdoByUserId(userInfo.getUserId());
			ShopVo shopVo = shopService.getShopVoByShopId(shopId);
			map.put("shopId", shopVo.getShopId());
			map.put("shopName", shopVo.getShopName());
		} catch (GenericException e) {
			e.printStackTrace();
		}

		String mobile = session.getAttribute("mobile").toString();

		if (mobile.equals("open")) {
			return new ModelAndView("/jsp-mobile/turnover/addFinancing_mobile", map);
		} else {
			return new ModelAndView("/turnover/addFinancing", map);
		}
	}

	@RequestMapping(value = "/saveFinancing.do", method = { RequestMethod.POST })
	@ResponseBody
	public String saveFinancing(FinancingVo c, PictureVo pictureVo, HttpSession session) {
		JSONObject json = new JSONObject();
		c.setCostDate(c.getDate());
		c.setTurnoverDate(c.getDate());
		try {
			if (c.getTurnoverjson() != null && !c.getTurnoverjson().equals("[]") && !c.getTurnoverjson().equals("")) {
				TurnoverPo tTurnoverPo = financingService.getTurnoverPo(c);
				if (tTurnoverPo == null) {
					json.put("success", false);
					json.put("msg", financingService.getMsg());
					return json.toString();
				}
				turnoverService.addTurnoverPo(tTurnoverPo);
				JSONArray array = JSONArray.fromObject(c.getTurnoverjson());
				BigDecimal valueTotal = new BigDecimal(0);

				for (int i = 0; i < array.size(); i++) {
					JSONObject object = JSONObject.fromObject(array.get(i));
					TurnoverSubPo tTurnoverSubPo = new TurnoverSubPo();
					tTurnoverSubPo.setTurnoverId(tTurnoverPo.getTurnoverId());
					tTurnoverSubPo.setTurnoverSubId(Long.valueOf(object.get("turnoverSubId").toString()));
					tTurnoverSubPo.setTurnoverValue(object.get("turnoverValue").toString());
					tTurnoverSubPo.setTurnoverType(Integer.valueOf(object.get("turnoverType").toString()));
					turnoverService.addTurnoverSub(tTurnoverSubPo);
					valueTotal = valueTotal.add(new BigDecimal(object.get("turnoverValue").toString()));
				}
				tTurnoverPo.setTurnoverValueTotal(valueTotal.toString());
				turnoverService.updateTurnoverPo(tTurnoverPo);
			}

			// 存储文件的路径
			String realPath = session.getServletContext().getRealPath("/");
			String filePath = realPath + File.separator + "jsp" + File.separator + "templet" + File.separator + "costFile";
			if (c.getCostjson() != null && !c.getCostjson().equals("[]") && !c.getCostjson().equals("")) {
				CostPo tcostPo = financingService.getCostPo(c);
				if (tcostPo == null) {
					json.put("success", false);
					json.put("msg", financingService.getMsg());
					return json.toString();
				}
				costService.addCostPo(tcostPo);
				JSONArray arrayCost = JSONArray.fromObject(c.getCostjson());
				BigDecimal valueTotalCost = new BigDecimal(0);

				for (int i = 0; i < arrayCost.size(); i++) {
					JSONObject objectCost = JSONObject.fromObject(arrayCost.get(i));
					CostSubPo tCostSubPo = new CostSubPo();
					tCostSubPo.setCostId(tcostPo.getCostId());
					tCostSubPo.setCostSubId(Long.valueOf(objectCost.get("costSubId").toString()));
					tCostSubPo.setCostValue(objectCost.get("costValue").toString());
					tCostSubPo.setCostType(Integer.valueOf(objectCost.get("costType").toString()));
					// 图片处理
					tCostSubPo = financingService.setPictureCost(pictureVo, tCostSubPo, filePath);

					costService.addCostSub(tCostSubPo);
					valueTotalCost = valueTotalCost.add(new BigDecimal(objectCost.get("costValue").toString()));
				}
				tcostPo.setCostValueTotal(valueTotalCost.toString());
				costService.updateCostPo(tcostPo);
			}

		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
		}
		json.put("success", true);
		return json.toString();
	}

	@RequestMapping(value = "/preUpdateFinancing.do", method = { RequestMethod.GET })
	public ModelAndView preUpdateFinancing(FinancingVo tFinancingVo, HttpSession session) {
		Map map = new HashMap();
		UserPo userInfo = (UserPo) session.getAttribute("user");
		try {
			// UserVo userVo =
			// userService.getUserVoById(String.valueOf(userInfo.getUserId()));
			long shopId = shopService.getShopIdoByUserId(userInfo.getUserId());
			ShopVo shopVo = shopService.getShopVoByShopId(shopId);
			tFinancingVo.setCustId(shopId);

			TurnoverPo tTurnoverPo = financingService.getTurnoverPoByDateAndCustId(tFinancingVo);
			if (tTurnoverPo != null) {
				BeanCopier copier = BeanCopier.create(TurnoverPo.class, FinancingVo.class, false);
				copier.copy(tTurnoverPo, tFinancingVo, null);

			}

			CostPo tCostPo = financingService.getCostPoByDateAndCustId(tFinancingVo);
			if (tCostPo != null) {

				BeanCopier copier1 = BeanCopier.create(CostPo.class, FinancingVo.class, false);
				copier1.copy(tCostPo, tFinancingVo, null);
			}
			tFinancingVo.setCustName(shopVo.getShopName());

			map.put("FinancingVo", tFinancingVo);

			// 设定页面初始 最大值
			map.put("addId", turnoverService.getMaxAddId(tFinancingVo));
			map.put("addIdCost", costService.getMaxAddId(tFinancingVo));

		} catch (GenericException e) {
			e.printStackTrace();
		}
		return new ModelAndView("/turnover/updateFinancing", map);
	}

	@RequestMapping(value = "/updateFinancing.do", method = { RequestMethod.POST })
	@ResponseBody
	public String updateFinancing(FinancingVo c, PictureVo pictureVo, HttpSession session) {
		JSONObject json = new JSONObject();

		try {
			financingService.deleteFinancing(c);
		} catch (GenericException e) {
			e.printStackTrace();
			json.put("success", true);
			return json.toString();
		}
		c.setCostId(0);
		c.setTurnoverId(0);

		saveFinancing(c, pictureVo, session);
		json.put("success", true);
		return json.toString();
	}

	@RequestMapping(value = "/preLookFinancing.do", method = { RequestMethod.GET })
	public ModelAndView preLookFinancing(FinancingVo tFinancingVo, HttpSession session) {
		Map map = new HashMap();
		UserPo userInfo = (UserPo) session.getAttribute("user");
		try {
			// UserVo userVo =
			// userService.getUserVoById(String.valueOf(userInfo.getUserId()));
			ShopVo shopVo = shopService.getShopVoByShopId(tFinancingVo.getCustId());

			TurnoverPo tTurnoverPo = financingService.getTurnoverPoByDateAndCustId(tFinancingVo);
			if (tTurnoverPo != null) {
				BeanCopier copier = BeanCopier.create(TurnoverPo.class, FinancingVo.class, false);
				copier.copy(tTurnoverPo, tFinancingVo, null);

			}

			CostPo tCostPo = financingService.getCostPoByDateAndCustId(tFinancingVo);
			if (tCostPo != null) {

				BeanCopier copier1 = BeanCopier.create(CostPo.class, FinancingVo.class, false);
				copier1.copy(tCostPo, tFinancingVo, null);
			}
			tFinancingVo.setCustName(shopVo.getShopName());

			map.put("FinancingVo", tFinancingVo);

			// 设定页面初始 最大值
			map.put("addId", turnoverService.getMaxAddId(tFinancingVo));
			map.put("addIdCost", costService.getMaxAddId(tFinancingVo));

		} catch (GenericException e) {
			e.printStackTrace();
		}
		return new ModelAndView("/turnover/lookFinancing", map);
	}

	@RequestMapping(value = "/downFinancing.do", method = { RequestMethod.GET })
	public void downFinancing(HttpServletResponse response, long costId, long costSubId, HttpSession session) {

		OutputStream toClient = null;

		try {
			String fileName = costService.getFileName(costId, costSubId);
			String realPath = session.getServletContext().getRealPath("/");
			String link = realPath + "jsp" + File.separator + "templet" + File.separator + "costFile" + File.separator + fileName;

			// path是指欲下载的文件的路径。
			File file = new File(link);
			// 取得文件名。

			String filename = file.getName();

			// 取得文件的后缀名。
			String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(link));

			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			// response.addHeader("Content-Disposition", "attachment;filename="
			// + new String(filename.getBytes()));

			response.setContentType("octets/stream");
			response.addHeader("Content-Type", "text/html; charset=utf-8");
			String fileName1 = new String(filename.getBytes("gbk"), "iso8859-1");
			response.addHeader("Content-Disposition", "attachment;filename=" + fileName1);

			toClient = new BufferedOutputStream(response.getOutputStream());
			toClient.write(buffer);

		} catch (UnsupportedEncodingException e1) {
		} catch (Exception e) {
		} finally {
			try {
				toClient.flush();
				toClient.close();
			} catch (IOException e) {
			}
		}
	}
}
